package com.atguigu.gmall.gateway.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;

/**
 * @author wk
 * @create 2021-08-26 11:02
 * 解决跨域问题方式一使用配置类
 * 方式二使用配置文件
 * 使用网关的跨域配置来实现，修改application.yml ,在spring.cloud.gateway节点添加配置
 *     gateway:
 *       globalcors:
 *         cors-configurations:
 *           '[/**]': # 匹配所有请求
 *             allowedHeaders: "*"
 *             allowedOrigins: "*" #跨域处理 允许所有的域
 *             allow-credentials: true
 *             allowedMethods:     # 支持的方法
 *               - GET
 *               - POST
 *               - PUT
 *               - DELETE
 *               - OPTION
 */
@Configuration
public class CorsConfig {

    @Bean
    public CorsWebFilter corsWebFilter(){

        // cors跨域配置对象
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.addAllowedOrigin("*");
        configuration.setAllowCredentials(true);
        configuration.addAllowedMethod("*");
        configuration.addAllowedHeader("*");

        // 配置源对象
        UrlBasedCorsConfigurationSource configurationSource = new UrlBasedCorsConfigurationSource();
        configurationSource.registerCorsConfiguration("/**", configuration);
        // cors过滤器对象
        return new CorsWebFilter(configurationSource);
    }
}
